<template>
  <!-- 避免事件冒泡的模态窗口的布局，将蒙层和登录盒子做成兄弟关系 -->
  <div class="login-modal">
    <!--  遮罩层独立一个空盒子 -->
    <div class="mask" @click="changeIsShowLoginModel(false)"></div>
    <div class="login-box">

      <!-- 关闭符号 -->
      <div class="close" @click="changeIsShowLoginModel(false)">
        <img src="../../assets/img/close.png" alt="" />
      </div>

      <!-- tab栏 -->
      <ul class="titles">
        <li @click="isShowFrom = true" :class="{ active: isShowFrom }">
          手机号登录
        </li>
        <li style="margin: 0 10px">|</li>
        <li @click="weixinClick" :class="{ active: !isShowFrom }">
          微信扫码登录
        </li>
      </ul>

      <!-- 表单 和 二维码 -->
      <div class="body">
        <div class="form" v-show="isShowFrom">
          <div class="ipt-group">
            <input
              type="text"
              placeholder="请输入手机号"
              maxlength="11"
              v-model.trim="phoneNumber"
            />
          </div>
          <div class="ipt-group mb20">
            <!-- w属性设置跟外层盒子一样会更丝滑 -->
            <slide-verify
              :l="42"
              :r="20"
              :w="281"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="ipt-group mb20">
            <input
              type="text"
              placeholder="请输入短信"
              maxlength="6"
              v-model.trim="SMScode"
            />
            <div class="btn" v-show="!isShowCount" @click="getVerifyCode">
              <span>获取验证码</span>
            </div>
            <div class="btn" v-show="isShowCount">
              <span>{{ count }} s</span>
            </div>
          </div>
          <div class="btn" @click="submit">登录</div>
        </div>
        <div id="weixin" class="wx-qrcode" v-show="!isShowFrom">

        </div>
      </div>
    </div>
  </div>
</template>

<script>
// vuex 相关
import { mapMutations,mapActions } from "vuex";
// 工具相关
import { validateTelephoneNumber } from "@/utils";
// 请求api相关
import { SendSMSAPI, loginAPI } from "@/request/loginApi.js";
export default {
  data() {
    return {
      // 是否展示登录表单
      isShowFrom: true,
      // 滑块提示语
      msg: "向右滑动",
      // 用户输入手机号
      phoneNumber: "",
      // 最大的计时时间
      countMax: 60,
      // 倒计时时间,每秒变化的那个数字
      count: 60,
      // 是否展示秒数所在盒子
      isShowCount: false,
      // 用户输入短信验证码
      SMScode: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModel: "isShowLogin/changeIsShowLoginModel",
      changeIsLogin: 'loginStatus/changeIsLogin',
    }),
    ...mapActions({
      asyncChangeIsShowToast: 'toastStatus/asyncChangeIsShowToast',
      asyncUpdateUserInfo: 'userInfo/asyncUpdateUserInfo'
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 点击获取验证码
    getVerifyCode() {
      // 验证抽取
      if (!this.toVerify()) { 
        return;
      }

      // 3.验证成功后发起请求获取验证码，  请求成功开始倒计时
      // 发请求
      // this.countDown()
      SendSMSAPI({
        phone: this.phoneNumber,
      })
        .then((res) => {
          if (res.code === 0) {
            this.countDown();
          } else {
            //获取短信验证码失败
            asyncChangeIsShowToast({
              msg: res.message,
              type: 'info'
            })

          }
        })
        .catch((err) => {
          // 发送请求失败
          console.log(err);
          this.asyncChangeIsShowToast({
            msg: '请求异常,请重新发送',
            type: 'info'
          })
        });
    },

    // 验证码倒计时
    countDown() {
      this.count = this.countMax; // 每次都要初始化一下倒计数
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          this.isShowCount = false;
          clearInterval(timer);
        }
      }, 1000);
    },

    toVerify() {
      //1.验证手机格式是否正确
      if (!validateTelephoneNumber(this.phoneNumber)) {
        this.asyncChangeIsShowToast({
          msg: '手机号码格式不正确',
          type: 'info'
        })
        return false;
      }

      // 2.验证拼图滑块是否验证通过
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncChangeIsShowToast({
          msg: '请滑动拼图到正确位置',
          type: 'info'
        })
        return false;
      }

      return true;
    },

    // 点击登录
    submit() {
      // 验证抽取
      // if (!this.toVerify()) {
      //   return;
      // }

      // if (!this.SMScode) {
      //   this.asyncChangeIsShowToast({
      //       msg: '请输入短信验证码',
      //       type: 'info'
      //   })
      //   return;
      // }
      // 先根据后端给到的测试账号和密码做登录。
      // 但如果真正场景要传的是短信验证码和手机号
      loginAPI({
        // phone:'13800138001',   //测试数据
        // password:'qwerty567',
        // phone: this.phoneNumber,
        // verifyCode: this.SMScode,
        phone: 123456,
        verifyCode: 454,
      }).then((res) => {
        if (res.code == 0) {
          // 1. 提示登陆成功
          this.asyncChangeIsShowToast({
            msg: '登录成功',
            type: 'success'
          })

          // 2. 保存token
          localStorage.setItem("x-auth-token", res["x-auth-token"]);

          // 3.隐藏登录框
          this.changeIsShowLoginModel(false)

          // 4.！！登陆状态切换
          this.changeIsLogin(true)

          // 5.更新用户信息
          this.asyncUpdateUserInfo()
        }else{
          this.asyncChangeIsShowToast({
            msg: res.message,
            type: 'info'
          })
        }
      });
    },

    // 点击切换到微信扫码登录
    weixinClick(){
      this.isShowFrom = false
      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d",  // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(window.btoa("http://127.0.0.1:8080" + _this.$route.path)),
        // 调用样式文件,下面是样式转成base64之后的编码
        // 在utils文件夹中打开cmd窗口，执行node data-url.js 即可生成下面编码
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    }

  }
};
</script>

<style scoped lang="less">
@import url("../../assets/css/public.less");

.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;

  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
  }

  .login-box {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../../assets/img/login-box-bg.png");

    .close {
      position: absolute;
      right: 60px;
      top: 20px;
      cursor: pointer;
    }

    .titles {
      margin-top: 60px;
      display: flex;
      justify-content: center;
      color: #ccc;

      li {
        cursor: pointer;
      }

      .active {
        color: #666;
      }
    }

    .body {
      margin-top: 20px;
      display: flex;
      justify-content: center;

      /* 短信表单样式 */
      .form {
        .ipt-group {
          display: flex;

          input {
            height: 48px;
            flex: 1;
            text-indent: 10px;
            border: 1px solid #ccc;
          }

          .btn {
            width: 100px;
            margin-left: 10px;
          }
        }
      }

      .btn {
        height: 50px;
        background-color: @base-color;
        text-align: center;
        line-height: 50px;
        color: #fff;
        cursor: pointer;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;

  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }

  .slide-verify-block {
    width: 85px;
    height: 136px;
  }

  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }

  &:hover {
    canvas {
      display: block;
    }

    .slide-verify-refresh-icon {
      display: block;
    }
  }
}

.wx-qrcode{
  display: flex;
  justify-content: center;
  padding-top: -20px;
}
</style>
